axios = require('axios')
ERROR = require "./_error.coffee"
PG = require('fckoa/db/pg')
{CACHE} = require('fckoa/db/redis')
send = require('fckoa/yun/smtp')
USER = require './_model/user'
SMSBAO = require "fckoa/config/smsbao"
{random} = require 'lodash'

class KeyPhone
    constructor: (@prefix) ->

    new : (phone)->
        code = random(0, 999999)
        await CACHE.setex(@prefix+phone, 9000, code)
        return (code+"").padStart(6,"0")

    verify: (phone, code)->
        key = @prefix+phone
        _code = await CACHE.get(key)
        if not _code
            return
        await CACHE.del(key)
        return (code - _code) == 0





KEY = new KeyPhone("auth/phone/new")

module.exports = require('fckoa/router') {

post:{

verify:(ctx)->
    {phone, code} = ctx.request.body
    if await KEY.verify(phone, code)
        ctx.body = await require('./_verify_key').phone.new(phone)
        return
    raise code:1

new : (ctx)->
    await require('./_captcha')(ctx)
    {phone,host} = ctx.request.body

    phone = phone.trim().replace(/(\s|\-)/g,'')

    if not /^(\+)?\d{4,}$/.test(phone)
        raise val:"手机号无效"

    txt = SMSBAO[2](host, "注册", await KEY.new(phone))

    if phone.startsWith("+")
        url = "w"
        phone = "%2b"+phone.slice(1)
    else
        url = ""
    url = "https://api.smsbao.com/#{url}sms?u=#{SMSBAO[0]}&p=#{SMSBAO[1]}&m=#{phone}&c=#{txt}"

    {data} = await axios.get(url)
    switch data
        when 0
            ctx.body = 0
        when 51
            raise val:"手机号码无效"
        else
            raise "出错了，请刷新页面重试"


}
}
